/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-25 11:39:54
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-06-26 15:19:17
 * @FilePath: \vite-project\src\components\common\CommonDrawer.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { Drawer, Space, type DrawerProps, Button, Form, type FormInstance, Spin } from 'antd';
import React from 'react';
import { useEffect, useState, createContext } from 'react';

interface CommonModalProps {
	close?: () => void;
	onSubmit?: (form?: any, callback?: () => void, modalCallback?: () => void) => Promise<void> | void;
	initFormData?: any;
	width?: number;
	isHideConfirm?: boolean;
	formLoading?: boolean;
	formDisabled?: boolean;
}

export const CommonDrawerContext = createContext<{
	form?: FormInstance<any>;
	formDisabled?: boolean;
}>({
	form: undefined,
});

const CommonDrawer: React.FC<CommonModalProps & DrawerProps> = props => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState<boolean>(false);

	function onClose() {
		form.resetFields();
		props?.close?.();
	}
	function onFinish(values: any) {
		if (props?.onSubmit) {
			setLoading(true);
			props?.onSubmit?.(values, () => setLoading(false), onClose);
		}
	}
	useEffect(() => {
		if (props.open) {
			form.setFieldsValue(props.initFormData || {});
		}
	}, [props.initFormData]);
	return (
		<Drawer
			destroyOnClose
			title={props.title}
			width={props.width || 500}
			onClose={onClose}
			open={props.open}
			extra={
				<Space>
					<Button onClick={onClose}>关闭</Button>
					{!props?.isHideConfirm ? (
						<Button loading={loading} htmlType="submit" type="primary" onClick={() => form.submit()}>
							保存
						</Button>
					) : null}
				</Space>
			}>
			<Spin spinning={!!props.formLoading}>
				<Form layout="vertical" form={form} onFinish={onFinish} disabled={props.formDisabled}>
					<CommonDrawerContext.Provider
						value={{
							form,
							formDisabled: props.formDisabled,
						}}>
						{props.children}
					</CommonDrawerContext.Provider>
				</Form>
			</Spin>
		</Drawer>
	);
};

export default React.memo(CommonDrawer);
